//
//  WQPicturePickerController.swift
//  1218-图片选择器
//
//  Created by 王先强 on 15/12/18.
//  Copyright © 2015年 王先强. All rights reserved.
//

import UIKit

private let WQPicturePickerCellID = "WQPicturePickerCellID"
private let WQPicturePickerMaxImageCount = 4

class WQPicturePickerController: UICollectionViewController {

    lazy var pictures = [UIImage]()
    private var selectedImageIndex = 0
    
    init(){
        super.init(collectionViewLayout: WQPicturePickerLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.collectionView?.backgroundColor = UIColor.whiteColor()
        self.collectionView!.registerClass(WQPicturePickerCell.self, forCellWithReuseIdentifier: WQPicturePickerCellID)

        // Do any additional setup after loading the view.
    }

    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return pictures.count + 1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WQPicturePickerCellID, forIndexPath: indexPath) as! WQPicturePickerCell
        cell.picturePickerDelegate = self

        if indexPath.item == WQPicturePickerMaxImageCount {//定义图片的最大张数，超出最大数目，cell隐藏
            cell.hidden = true
        }else{//小于最大张数就显示
            cell.hidden = false
            cell.selectedImage = (indexPath.item < pictures.count) ? pictures[indexPath.item] : nil
        }
        
    
        return cell
    }
    
    
    private class WQPicturePickerLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
            super.prepareLayout()
            
            let maxCountPerRow: CGFloat = 4
            let miniMargin: CGFloat = 4
            collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
            let margin = UIScreen.mainScreen().scale * miniMargin
            let itemWH = (collectionView!.bounds.size.width - margin * (maxCountPerRow + 1)) / maxCountPerRow
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
            itemSize = CGSize(width: itemWH, height: itemWH)
            sectionInset = UIEdgeInsetsMake(margin,margin,margin,margin)
            
            
        }
    }

}


extension WQPicturePickerController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

        var image = info[UIImagePickerControllerOriginalImage] as! UIImage

        //对传入对图片进行大小处理，过大就加载指定大小图片
        image = image.resizePictureFromWith(600)
        if selectedImageIndex < pictures.count {
            //点击的是已经选择的图片，进行图片替换
            pictures[selectedImageIndex] = image
        }else{//点击的是加号按钮，添加图片
            pictures.append(image)
        }
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }

}

// MARK: - WQPicturePickerCellDelegate 实现cell的代理协议
extension WQPicturePickerController: WQPicturePickerCellDelegate{
    //点击加号按钮访问相册
    @objc private func picturePickerCellDidClickedAdd(cell: WQPicturePickerCell) {
//       let indexPath = collectionView?.indexPathForCell(cell)
//        print("addPicture \(indexPath!.item)")
        
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            print("无法访问照片库")
            return
        }
        
        let indexPath = collectionView?.indexPathForCell(cell)
        //纪录被点击的cell下标
        selectedImageIndex = (indexPath?.item)!
        
        let pickerVc = UIImagePickerController()
        pickerVc.delegate = self
        
        presentViewController(pickerVc, animated: true, completion: nil)
        
    }
    //点击删除按钮，删除已经选择对图片
    @objc private func picturePickerCellDidClickedDelete(cell: WQPicturePickerCell) {
        let indexPath = collectionView?.indexPathForCell(cell)
        pictures.removeAtIndex(indexPath!.item)
        collectionView?.reloadData()

    }
    

}



///  创建cell的代理协议
@objc
private protocol WQPicturePickerCellDelegate: NSObjectProtocol {
    func picturePickerCellDidClickedDelete(cell: WQPicturePickerCell)
    func picturePickerCellDidClickedAdd(cell: WQPicturePickerCell)
}
/// 自定义WQPicturePickerCell
class WQPicturePickerCell: UICollectionViewCell {
    /// 定义代理属性
    private weak var picturePickerDelegate: WQPicturePickerCellDelegate?
    var selectedImage: UIImage? {
        didSet{
            
            //判断图片是不是最后一张
            if selectedImage == nil {
                addButton.setImage(UIImage(named: "compose_pic_add"), forState: .Normal)
                deleteButton.hidden = true
            }else{
                addButton.setImage(selectedImage, forState: .Normal)
                deleteButton.hidden = false
            }
            
        }
    }
    
    /// 懒加载控件
    lazy var addButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        btn.sizeToFit()
        return btn
    }()
    lazy var deleteButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        btn.sizeToFit()
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    private func setupUI() {
        addSubview(addButton)
        addSubview(deleteButton)
        addButton.frame = self.bounds
        deleteButton.hidden = true
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(self.snp_right)
            make.top.equalTo(self.snp_top)
        }
        
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        deleteButton.addTarget(self, action: "deletePicture", forControlEvents: .TouchUpInside)
    }
    
    @objc private func addPicture() {
        
        picturePickerDelegate?.picturePickerCellDidClickedAdd(self)
    }
    
    @objc private func deletePicture() {
      
        picturePickerDelegate?.picturePickerCellDidClickedDelete(self)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

